#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" 微信小程序控制器
"""
import json
import base64
import tornado
from tornado.escape import json_decode
from trest.router import get
from trest.router import put
from trest.router import post
from trest.router import delete
from trest.logger import SysLogger
from trest.exception import JsonError
from trest.utils.encrypter import AESEncrypter
from applications.ishici.services.wxamp import WxampSercice

from .common import CommonHandler


class SaveUserinfoHandler(CommonHandler):
    @post('/v1/user')
    def v1_user_post(self, *args, **kwargs):
        """ 获取用户信息之后绑定用户信息
        """
        args = json_decode(self.request.body)
        appid = args.get('appid', None)
        openid = args.get('openid', None)
        info = args.get('info', None)
        result = WxampSercice.save_userinfo(appid, openid, info)
        return self.success(data = result)


class ShareinfoHandler(CommonHandler):
    @get('/v1/shareinfo')
    def v1_openid_get(self, *args, **kwargs):
        """ 判断是否是从微信群内打开该程序的
        """
        appid = self.get_argument('appid', None)
        key = self.get_argument('sessionKey', None)
        iv = self.get_argument('iv', None)
        cipher = self.get_argument('encryptedData', None)

        if len(skey) != 24:
            raise JsonError('Session key error')
        if len(iv) != 24:
            raise JsonError('IV error')

        aes_key = base64.b64decode(key)
        aes_iv = base64.b64decode(iv)
        # aes_cipher  = base64.b64decode(cipher)
        aes = AESEncrypter(aes_key, aes_iv)
        res = aes.decrypt(cipher)
        if res:
            res = base64.b64decode(res)

        return self.success(data = res)
